import 'http_service.dart';
import '../models/api_response_model.dart';
import '../models/contact_model.dart';
import '../models/repair_order_model.dart';

/// API服务类
/// 包含所有业务相关的API接口调用
class ApiService {
  static final HttpService _httpService = HttpService.instance;
  
  // ==================== 用户认证相关 ====================
  
  /// 用户注册
  static Future<RegisterResponse> register({
    required String username,
    required String tel,
    required String password,
    required String confirmPassword,
    required String verifyCode,
    String? address,
    String? shopName,
    String? channel,
  }) async {
    final response = await _httpService.post<Map<String, dynamic>>(
      '/register/addNewUser4', 
      body: {
        'username': username,
        'tel': tel,
        'pwd': password,
        'code': verifyCode,
        'address': address ?? '',
        'shopname': shopName ?? '',
        'downchannel': channel ?? '',
        'viplevel': '1', // VIP等级，默认为1
        'udid': '', // 设备ID，需要从设备获取
        'ostype': 'flutter',
        'version': '1.0.0',
        'city': '',
      },
    );

    if (response.isSuccess && response.data != null) {
      return RegisterResponse(
        success: true,
        message: response.message,
        userId: response.data?['_id']?.toString(),
        token: response.data?['token']?.toString(),
      );
    } else {
      return RegisterResponse(
        success: false,
        message: response.message,
      );
    }
  }
  
  /// 用户登录
  static Future<LoginResponse> login({
    required String username,
    required String password,
    required bool isEmployee,
  }) async {
    final endpoint = isEmployee ? '/employee/login2' : '/users/login4';
    final response = await _httpService.post<Map<String, dynamic>>(
      endpoint, 
      body: {
        'username': username, // 用户名
        'tel': username, // 手机号（与username相同）
        'pwd': password,
        'udid': 'flutter_device_${DateTime.now().millisecondsSinceEpoch}', // 设备ID
        'ostype': 'flutter',
        'pushid': 'flutter_push_${DateTime.now().millisecondsSinceEpoch}', // 推送ID
        'version': '1.0.0',
        'isfirstlogin': '0',
      },
    );

    if (response.isSuccess && response.data != null) {
      return LoginResponse(
        success: true,
        message: response.message,
        userData: UserLoginData.fromJson(response.data!),
      );
    } else {
      return LoginResponse(
        success: false,
        message: response.message,
      );
    }
  }
  
  /// 获取验证码
  static Future<VerifyCodeResponse> getVerifyCode(String tel) async {
    final response = await _httpService.post<Map<String, dynamic>>(
      '/sms/sendSmsCode', 
      body: {'tel': tel},
    );

    return VerifyCodeResponse(
      success: response.isSuccess,
      message: response.message,
      code: response.data?['code']?.toString(),
    );
  }
  
  /// 重置密码
  static Future<ApiResponse<bool>> resetPassword({
    required String tel,
    required String newPassword,
    required String verifyCode,
  }) async {
    return await _httpService.post<bool>(
      '/users/resetPwd', 
      body: {
        'tel': tel,
        'pwd': newPassword,
        'code': verifyCode,
      },
      fromJsonT: (data) => true,
    );
  }
  
  // ==================== 客户管理相关 ====================
  
  /// 添加客户
  static Future<ApiResponse<Contact>> addContact(Contact contact) async {
    return await _httpService.post<Contact>(
      '/contact/add', 
      body: contact.toJson(),
      fromJsonT: (data) => Contact.fromJson(data),
    );
  }
  
  /// 更新客户信息
  static Future<ApiResponse<Contact>> updateContact(Contact contact) async {
    return await _httpService.post<Contact>(
      '/contact/update', 
      body: contact.toJson(),
      fromJsonT: (data) => Contact.fromJson(data),
    );
  }
  
  /// 删除客户
  static Future<ApiResponse<bool>> deleteContact(String contactId) async {
    return await _httpService.post<bool>(
      '/contact/delete', 
      body: {'id': contactId},
      fromJsonT: (data) => true,
    );
  }
  
  /// 查询所有客户
  static Future<ApiResponse<List<Contact>>> getAllContacts(String ownerTel) async {
    print('=== 客户查询接口调试信息 ===');
    print('用户手机号: $ownerTel');
    print('请求路径: /contact/queryAll');
    print('请求参数: {"owner": "$ownerTel"}');
    print('调用堆栈: ${StackTrace.current}');
    print('警告：客户接口被调用！');
    
    // 尝试不同的API路径
    final response = await _httpService.post<List<Contact>>(
      '/contact/queryAll', 
      body: {
        'owner': ownerTel,
        'userTel': ownerTel,  // 添加备用参数名
        'phone': ownerTel,    // 添加另一个可能的参数名
      },
      fromJsonT: (data) {
        print('客户API返回数据: $data');
        if (data is List) {
          print('客户数据是列表，长度: ${data.length}');
          try {
            return data.map((e) => Contact.fromJson(e as Map<String, dynamic>)).toList();
          } catch (e) {
            print('客户数据解析失败: $e');
            return <Contact>[];
          }
        }
        print('客户数据不是列表，返回空列表');
        return <Contact>[];
      },
    );
    
    print('API响应结果: 成功=${response.isSuccess}, 消息=${response.message}');
    print('=== 客户查询接口调试信息结束 ===');
    
    return response;
  }
  
  /// 搜索客户
  static Future<ApiResponse<List<Contact>>> searchContacts(String keyword) async {
    return await _httpService.post<List<Contact>>(
      '/contact/search', 
      body: {'keyword': keyword},
      fromJsonT: (data) {
        if (data is List) {
          try {
            return data.map((e) => Contact.fromJson(e as Map<String, dynamic>)).toList();
          } catch (e) {
            print('搜索客户数据解析失败: $e');
            return <Contact>[];
          }
        }
        return <Contact>[];
      },
    );
  }
  
  // ==================== 工单管理相关 ====================
  
  /// 添加工单
  static Future<ApiResponse<RepairOrder>> addRepairOrder(RepairOrder repairOrder) async {
    return await _httpService.post<RepairOrder>(
      '/repair/add', 
      body: repairOrder.toJson(),
      fromJsonT: (data) => RepairOrder.fromJson(data),
    );
  }
  
  /// 更新工单
  static Future<ApiResponse<RepairOrder>> updateRepairOrder(RepairOrder repairOrder) async {
    return await _httpService.post<RepairOrder>(
      '/repair/update', 
      body: repairOrder.toJson(),
      fromJsonT: (data) => RepairOrder.fromJson(data),
    );
  }
  
  /// 删除工单
  static Future<ApiResponse<bool>> deleteRepairOrder(String repairId) async {
    return await _httpService.post<bool>(
      '/repair/delete', 
      body: {'id': repairId},
      fromJsonT: (data) => true,
    );
  }
  
  /// 查询所有工单
  static Future<ApiResponse<List<RepairOrder>>> getAllRepairOrders(String ownerTel) async {
    print('=== 工单查询接口调试信息 ===');
    print('用户手机号: $ownerTel');
    print('请求路径: /repair/queryAll');
    print('请求参数: {"owner": "$ownerTel"}');
    
    return await _httpService.post<List<RepairOrder>>(
      '/repair/queryAll', 
      body: {
        'owner': ownerTel,
        'userTel': ownerTel,  // 添加备用参数名
        'phone': ownerTel,    // 添加另一个可能的参数名
      },
      fromJsonT: (data) {
        print('工单API返回数据: $data');
        print('数据类型: ${data.runtimeType}');
        if (data is List) {
          print('工单数据是列表，长度: ${data.length}');
          try {
            final result = data.map((e) {
              print('转换工单数据项: $e');
              print('数据项类型: ${e.runtimeType}');
              if (e is Map<String, dynamic>) {
                print('字段列表: ${e.keys.toList()}');
                print('carcode: ${e['carcode']}');
                print('cartype: ${e['cartype']}');
                print('name: ${e['name']}');
                print('tel: ${e['tel']}');
                print('customerstatus: ${e['customerstatus']}');
                print('serviceitem: ${e['serviceitem']}');
                print('entrytime: ${e['entrytime']}');
                print('pickuptime: ${e['pickuptime']}');
                print('paymentmethod: ${e['paymentmethod']}');
                print('actualamount: ${e['actualamount']}');
                print('discountamount: ${e['discountamount']}');
                print('repairtype: ${e['repairtype']}');
              }
              return RepairOrder.fromJson(e as Map<String, dynamic>);
            }).toList();
            print('成功转换 ${result.length} 个工单对象');
            return result;
          } catch (e) {
            print('工单数据解析失败: $e');
            return <RepairOrder>[];
          }
        }
        print('工单数据不是列表，返回空列表');
        return <RepairOrder>[];
      },
    );
  }

  /// 根据状态查询工单
  static Future<ApiResponse<List<RepairOrder>>> getRepairOrdersByStatus(String ownerTel, String status) async {
    // 将中文状态转换为API参数
    String statusParam = '';
    switch (status) {
      case '维修中':
        statusParam = 'inProgress';
        break;
      case '已修完':
        statusParam = 'completed';
        break;
      case '已提车':
        statusParam = 'pickedUp';
        break;
      case '已取消':
        statusParam = 'cancelled';
        break;
      case '挂账中':
        statusParam = 'onAccount';
        break;
      default:
        statusParam = '';
    }

    print('=== 状态工单查询接口调试信息 ===');
    print('用户手机号: $ownerTel');
    print('状态: $status -> $statusParam');
    print('请求路径: /repair/queryAll (带状态参数)');
    print('请求参数: {"owner": "$ownerTel", "status": "$statusParam", "type": "$statusParam"}');
    
    return await _httpService.post<List<RepairOrder>>(
      '/repair/queryAll', 
      body: {
        'owner': ownerTel,
        'userTel': ownerTel,  // 添加备用参数名
        'phone': ownerTel,    // 添加另一个可能的参数名
        'status': statusParam,
        'type': statusParam,   // 尝试不同的参数名
      },
      fromJsonT: (data) {
        print('状态工单API返回数据: $data');
        print('数据类型: ${data.runtimeType}');
        if (data is List) {
          print('状态工单数据是列表，长度: ${data.length}');
          try {
            final result = data.map((e) {
              print('转换状态工单数据项: $e');
              return RepairOrder.fromJson(e as Map<String, dynamic>);
            }).toList();
            print('成功转换 ${result.length} 个状态工单对象');
            return result;
          } catch (e) {
            print('状态工单数据解析失败: $e');
            return <RepairOrder>[];
          }
        }
        print('状态工单数据不是列表，返回空列表');
        return <RepairOrder>[];
      },
    );
  }
  
  /// 查询客户的工单
  static Future<ApiResponse<List<RepairOrder>>> getContactRepairOrders(String contactId) async {
    return await _httpService.post<List<RepairOrder>>(
      '/repair/queryByContact', 
      body: {'contactId': contactId},
      fromJsonT: (data) {
        if (data is List) {
          try {
            return data.map((e) => RepairOrder.fromJson(e as Map<String, dynamic>)).toList();
          } catch (e) {
            print('客户工单数据解析失败: $e');
            return <RepairOrder>[];
          }
        }
        return <RepairOrder>[];
      },
    );
  }
  
  /// 查询今日工单统计（已废弃，使用getAllRepairOrders代替）
  @deprecated
  static Future<ApiResponse<Map<String, dynamic>>> getTodayServiceInfo() async {
    return ApiResponse<Map<String, dynamic>>(
      success: false,
      code: 'DEPRECATED',
      message: '此接口已废弃，请使用getAllRepairOrders',
      data: null,
      statusCode: 0,
    );
  }
  
  // ==================== 其他功能 ====================
  
  /// 检查版本更新
  static Future<ApiResponse<Map<String, dynamic>>> checkVersion() async {
    return await _httpService.get<Map<String, dynamic>>(
      '/update/android',
      fromJsonT: (data) => data as Map<String, dynamic>,
    );
  }
  
  /// 更新用户头像
  static Future<ApiResponse<String>> updateAvatar(String filePath) async {
    return await _httpService.uploadFile<String>(
      '/users/updateAvatar',
      filePath: filePath,
      fileName: 'avatar.jpg',
      fromJsonT: (data) => data.toString(),
    );
  }
  
  /// 更新用户信息
  static Future<ApiResponse<bool>> updateUserInfo({
    String? username,
    String? address,
    String? shopName,
  }) async {
    return await _httpService.post<bool>(
      '/users/updateInfo', 
      body: {
        if (username != null) 'username': username,
        if (address != null) 'address': address,
        if (shopName != null) 'shopname': shopName,
      },
      fromJsonT: (data) => true,
    );
  }
}
